package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //参数校验
        if(dto==null){
            
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        dto.checkParam();
        //分页查询
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        IPage<ApUserRealname> pageParam = new Page<>(dto.getPage(),dto.getSize());


        if(dto.getStatus()!=null){
            lambdaQueryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }

        IPage<ApUserRealname> page = page(pageParam, lambdaQueryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
//        return ResponseResult.okResult(pageResponseResult);

        return pageResponseResult;
    }


    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    ArticleFeign articleFeign;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)

    public ResponseResult updateStatusById(AuthDto dto, Short status) {


        //1.检查参数
        if(dto==null||dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询ap_user_realname
        ApUserRealname apUserRealname = getById(dto.getId());
        if(apUserRealname==null||apUserRealname.getUserId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2.获取当前ap_user的id
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if(apUser==null||apUser.getStatus()){
            return ResponseResult.errorResult(AppHttpCodeEnum.APUSER_LOCKED);
        }
        //3.修改状态
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //4.如果状态为通过
        if(status.intValue()==(AdminConstants.PASS_AUTH).intValue()){
            //4.1远程创建自媒体账号
            WmUser wmUser = creatWmUser(dto,apUser);
            if(wmUser==null||wmUser.getId()==null){
                CustException.cust(AppHttpCodeEnum.WMUSER_ADD_ERROR);
            }
            //4.2远程创建作者账号
            Boolean flag = createApAuthor(wmUser);
            if(!flag){
                CustException.cust(AppHttpCodeEnum.AUTHOR_ADD_ERROR);
            }

        }

        //5.更新flag,设为1
        apUser.setFlag((short) 1);
        //6.返回结果
        apUserMapper.updateById(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //创建作者账户
    private Boolean createApAuthor(WmUser wmUser) {
        boolean flag = false;
        ApAuthor Author = articleFeign.findByUserId(wmUser.getApUserId());
        if(Author==null){
            ApAuthor apAuthor = new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setName(wmUser.getName());
            apAuthor.setWmUserId(wmUser.getId());
            apAuthor.setType(AdminConstants.AUTHOR_TYPE);
            ResponseResult responseResult = articleFeign.save(apAuthor);

            //判断
            if(responseResult.getCode()==0){
                return flag=true;
            }
        }

        return flag;
    }

    //创建自媒体在账户的方法
    private WmUser creatWmUser(AuthDto dto, ApUser apUser) {
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if(wmUser==null){
            wmUser = new WmUser();
            wmUser.setName(apUser.getName());
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setScore(0);
            wmUser.setStatus(9);
            wmUser.setType(0);

            return wemediaFeign.save(wmUser);
        }
        return null;
    }
}
